import AsyncStorage from '@react-native-async-storage/async-storage';
import { api } from './api';
import { AUTH_API } from '../config/apiConfig';

/**
 * 用户认证工具类
 * 提供登录、登出、token管理等功能
 */
export const auth = {
  // 用户登录
  login: async (username, password) => {
    try {
      const response = await api.post(AUTH_API.LOGIN, {
        username,
        password
      });
      
      if (response.success) {
        // 存储token和用户信息
        await AsyncStorage.setItem('userToken', response.token);
        await AsyncStorage.setItem('userInfo', JSON.stringify(response.user));
        await AsyncStorage.setItem('tokenExpireTime', response.expireTime.toString());
      }
      
      return response;
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  },
  
  // 用户登出
  logout: async () => {
    try {
      // 清除存储的用户信息和token
      await AsyncStorage.removeItem('userToken');
      await AsyncStorage.removeItem('userInfo');
      await AsyncStorage.removeItem('tokenExpireTime');
    } catch (error) {
      console.error('登出失败:', error);
      throw error;
    }
  },
  
  // 验证token有效性
  validateToken: async () => {
    try {
      const token = await AsyncStorage.getItem('userToken');
      if (!token) {
        return false;
      }
      
      // 检查token是否过期
      const expireTime = await AsyncStorage.getItem('tokenExpireTime');
      if (expireTime) {
        const currentTime = new Date().getTime();
        if (currentTime > parseInt(expireTime)) {
          // token已过期，清除存储
          await auth.logout();
          return false;
        }
      }
      
      // 调用后端验证接口
      const response = await api.get(AUTH_API.VALIDATE);
      return response.valid;
    } catch (error) {
      console.error('验证token失败:', error);
      // 验证失败时，清除存储的token
      await AsyncStorage.removeItem('userToken');
      return false;
    }
  },
  
  // 获取用户信息
  getUserInfo: async () => {
    try {
      const userInfo = await AsyncStorage.getItem('userInfo');
      return userInfo ? JSON.parse(userInfo) : null;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return null;
    }
  },
  
  // 检查用户是否已登录
  isLoggedIn: async () => {
    try {
      const token = await AsyncStorage.getItem('userToken');
      return token !== null;
    } catch (error) {
      console.error('检查登录状态失败:', error);
      return false;
    }
  },
  
  // 获取存储的token
  getToken: async () => {
    try {
      return await AsyncStorage.getItem('userToken');
    } catch (error) {
      console.error('获取token失败:', error);
      return null;
    }
  }
};